﻿using System;
using System.Collections.Generic;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using CreditAgricole.Framework;

namespace CreditAgricole.CommonElements.Event_Receivers.ProductionDeploymentEventReceivers
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class ProductionDeploymentEventReceivers : SPItemEventReceiver
    {
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            bool currentFiringStatus = this.EventFiringEnabled;

            try
            {
                this.EventFiringEnabled = false;
                properties.ListItem[SPCreditAgricoleFieldId.ProductionDeploymentStatus] = properties.List.Fields[SPCreditAgricoleFieldId.ProductionDeploymentStatus].DefaultValue; // Set Deployment status to the default field value ("Pas en Production")
                properties.ListItem[SPCreditAgricoleFieldId.Title] = properties.ListItem[SPBuiltInFieldId.FileLeafRef]; // Title is the filename by default
                properties.ListItem.SystemUpdate();
                CALoggingHelper.AddInformationEntry(string.Format("Item added to the {0} list. Field {1} set to default value ({2}).", properties.List.Title, properties.List.Fields[new Guid("{817ab77a-0ac2-49bb-8010-d56b0a1089cc}")].StaticName, properties.List.Fields[new Guid("{817ab77a-0ac2-49bb-8010-d56b0a1089cc}")].DefaultValue.ToString()));
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(ex.Message)) CALoggingHelper.AddErrorEntry(ex.Message);
            }
            finally
            {
                this.EventFiringEnabled = currentFiringStatus;
            }
        }

        /// <summary>
        /// An item was updated
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            bool currentFiringStatus = this.EventFiringEnabled;
            try
            {
                this.EventFiringEnabled = false;
                if (properties.ListTitle.ToLower() == Constants.ChangingListTitle)
                {
                    // if status is not defined, it will be set to default value (must be done here because default content type doesn't include this field)
                    // this can happens if solution is retracted then deployed and feature has not been deactivated/reactivated (or if iis application needs to be recycled).
                    // In this case, the event receiver are no more attached to the list and the status can be blank if a user adds some documents during this period.
                    if (string.IsNullOrEmpty(properties.ListItem[SPCreditAgricoleFieldId.ProductionDeploymentStatus] as string))
                    {
                        properties.ListItem[SPCreditAgricoleFieldId.ProductionDeploymentStatus] = properties.List.Fields[SPCreditAgricoleFieldId.ProductionDeploymentStatus].DefaultValue; // Pas en Production
                        properties.ListItem.SystemUpdate();
                    }

                    bool? resubmit = properties.ListItem[SPCreditAgricoleFieldId.ResubmitWorkflow] as bool?; // Get Resubmit WF value
                    if (resubmit == true)
                    {
                        // Reset checkbox for resubmit and reset content type to Unapproved
                        properties.ListItem[SPCreditAgricoleFieldId.ResubmitWorkflow] = false;
                        properties.ListItem["ContentTypeId"] = properties.ListItem.ParentList.ContentTypes["Production Deployment Unapproved"].Id;
                        properties.ListItem.SystemUpdate();
                        CALoggingHelper.AddInformationEntry("Contenttype changed to Production Deployment Unapproved.");
                        //CALoggingHelper.AddInformationEntry(string.Format("Attempting to resubmit approval workflow for document '{0}'...", properties.ListItem.Name));
                        SPHelper.StartWorkflow(properties.ListItem, true, 0);
                    }
                    else if (!string.IsNullOrEmpty(properties.ListItem.Name)) // if() added because event viewer logging reported 2 attempts to start workflow at the same time, one document of witch is empty.
                    {
                        // Start the workflow only if there is none already associated with the item
                        //CALoggingHelper.AddInformationEntry(string.Format("Attempting to start approval workflow for document '{0}'...", properties.ListItem.Name));
                        SPHelper.StartWorkflow(properties.ListItem);
                    }
                }
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(ex.Message)) CALoggingHelper.AddErrorEntry(ex.Message);
            }
            finally
            {
                this.EventFiringEnabled = currentFiringStatus;
            }
        }
    }
}
